<template>
  <div class="form-item" :class="{ 'has-error': showError, 'is-mobile': isMobile, 'is-horizontal': layout === 'horizontal' }">
    <label v-if="label" class="form-label">
      <span>{{ label }}</span>
      <span v-if="required" class="required-mark">*</span>
    </label>
    <div class="form-content">
      <slot></slot>
    </div>
    <div v-if="showError" class="error-message">{{ error }}</div>
    <div v-if="hint && !showError" class="hint-message">{{ hint }}</div>
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'FormItem',
  props: {
    label: {
      type: String,
      default: ''
    },
    required: {
      type: Boolean,
      default: false
    },
    error: {
      type: String,
      default: ''
    },
    hint: {
      type: String,
      default: ''
    },
    layout: {
      type: String,
      default: 'vertical',
      validator: value => ['vertical', 'horizontal'].includes(value)
    }
  },
  computed: {
    ...mapState('app', ['device']),
    isMobile() {
      return this.device === 'mobile'
    },
    showError() {
      return !!this.error
    }
  }
}
</script>

<style scoped>
.form-item {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.required-mark {
  color: #f5222d;
  margin-left: 4px;
}

.form-content {
  position: relative;
}

.error-message {
  font-size: 12px;
  color: #f5222d;
  margin-top: 4px;
}

.hint-message {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.has-error :deep(.form-input), 
.has-error :deep(.form-select), 
.has-error :deep(.form-textarea) {
  border-color: #f5222d;
}

.has-error :deep(.form-input:focus), 
.has-error :deep(.form-select:focus), 
.has-error :deep(.form-textarea:focus) {
  box-shadow: 0 0 0 2px rgba(245, 34, 45, 0.2);
}

/* 水平布局 */
.is-horizontal {
  display: flex;
  align-items: flex-start;
}

.is-horizontal .form-label {
  min-width: 120px;
  margin-right: 16px;
  margin-bottom: 0;
  padding-top: 10px;
  text-align: right;
  flex-shrink: 0;
}

.is-horizontal .form-content {
  flex: 1;
  min-width: 0;
}

.is-horizontal .error-message,
.is-horizontal .hint-message {
  margin-left: 136px;
}

/* 移动端优化 */
.is-mobile .form-label {
  font-size: var(--font-size-sm);
  margin-bottom: 10px;
}

.is-mobile .error-message,
.is-mobile .hint-message {
  font-size: var(--font-size-xs);
  margin-top: 6px;
}

/* 移动端下强制垂直布局 */
.is-mobile.is-horizontal {
  flex-direction: column;
}

.is-mobile.is-horizontal .form-label {
  min-width: auto;
  margin-right: 0;
  margin-bottom: 10px;
  padding-top: 0;
  text-align: left;
}

.is-mobile.is-horizontal .error-message,
.is-mobile.is-horizontal .hint-message {
  margin-left: 0;
}

/* 移动端标签字体不宜过小 */
.is-mobile .form-label {
  font-weight: 500;
}

/* 移动端错误提示更明显 */
.is-mobile .error-message {
  padding: 4px 0;
}
</style> 